import Vue from 'vue'
import Vuex from 'vuex'
import jwt_decode from "jwt-decode";

// 解析token
//解析token,存储到vuex中,防止浏览器刷新后数据丢失问题
let user = {}
const token = localStorage.getItem('eleToken')
if(token) {
  user = jwt_decode(token).rule;
}
//获取localStorage里面的激活的选项，并解析
const option = JSON.parse(localStorage.getItem('activeMenu'))

Vue.use(Vuex)
const state = {
  isAuthenticated:user !== null?true : false, // 是否认证通过
  user:user || {}, // 用户信息
  isDay:true,
  activeMenu:option || {}
}
//获取仓库里面的数据
const getters = {
  isAuthenticated: state => state.isAuthenticated,
  user: state => state.user,
  isDay: state => state.isDay,
  getActiveMenu: state => state.activeMenu
}
const mutations = {
  SET_AUTHENTICATED(state, isAuthenticated) {
    if (isAuthenticated) state.isAuthenticated = isAuthenticated
    else state.isAuthenticated = false
  },
  SET_USER(state, user) {
    if (user) state.user = user
    else state.user = {}
  },
  SET_ISDAY(state,isDay) {
    if(isDay) state.isDay = isDay
    else state.isDay = false
  },
  SET_ACTIVE_MENU(state,option) {
    if(option) state.activeMenu = option
    else state.activeMenu = {}
  }
}
const actions = {
  setAuthenticated({ commit }, isAuthenticated) {
    commit('SET_AUTHENTICATED', isAuthenticated)
  },
  setUser({ commit }, user) {
    commit('SET_USER', user)
  },
  clearState({commit}) {
    commit('SET_AUTHENTICATED',false)
    commit('SET_USER',null)
  },
  setIsDay({commit},isDay) {
    commit('SET_ISDAY', isDay)
  },
  setActiveMenu({commit},option) {
    commit('SET_ACTIVE_MENU',option)
  }
}
export default new Vuex.Store({
  state,
  getters,
  mutations,
  actions,
})
